#!/usr/bin/python

import requests
import xlwt
import time
from load_my_gitee_config import *

def time_clean(str, j):
    if str:
        for d in j:
            str = str.replace(d, '')
        return str.replace('T', ' ')
    return "none"

cfg = load_gitee_config_and_update_token()
org = cfg.get('org')
token = cfg.get('access_token')

my_repo_pattern = cfg.get('my_repo_pattern')
if not my_repo_pattern:
    my_repo_pattern = ""

body_del = cfg.get('body_del')
if not body_del:
    body_del = []

time_del = []

if len(org) == 0 or len(token) == 0:
    quit();

headers = { 'Content-Type': 'application/json',
        'charset' : 'UTF-8' }

all_name=[]
page = 0
while True:
    page += 1
    url="https://gitee.com/api/v5/orgs/{:s}/repos".format(org)
    params = {'access_token' : token,
            'type' : 'all',
            'page' : page,
            'per_page' : '100'}
    r = requests.get(url = url, headers = headers, params = params)
    data = r.json()
    if len(data) == 0:
        break

    for d in data:
        if my_repo_pattern in d['name']:
            all_name.append(d['name'])

f = xlwt.Workbook()

pr_total_cnt = 0
sum = len(all_name)
print("get {:} repos".format(sum))
for name in all_name:
    pr_cnt = 0
    pr_url="https://gitee.com/api/v5/repos/{:s}/{:s}/pulls".format(org, name)

    print("\nREPO: {:}".format(name))
    page = 0;
    while True:
        page += 1
        params = { 'state' : 'all',
                'sort' : 'created',
                'direction' : 'desc',
                'page' : page,
                'per_page' : '20'}
        pr_r = requests.get(url = pr_url, params = params, headers = headers)
        data = pr_r.json()
        if len(data) == 0:
            break

        sheet = f.add_sheet(name[-30:], cell_overwrite_ok=True)
        row0 = ["title", "url", "status", "create time", "merged time", "user", "assignees"]
        for i in range(0,len(row0)):
            sheet.write(0,i,row0[i])

        for d in data:
            pr_cnt += 1
            assignees = []
            for a in d['assignees']:
                assignees.append(a['login'])
            print("  PR {:}, assignees: {:}, create: {:}, merged:{:}".format(pr_cnt, assignees, time_clean(d['created_at'], time_del), time_clean(d['merged_at'], time_del)))
            print("    title: {:} ,body:".format(d['title'][:32]))
            print("    url: {:}".format(d['html_url']))
            ii = 0
            sheet.write(pr_cnt, ii, d['title'])
            ii = ii + 1
            sheet.write(pr_cnt, ii, d['html_url'])
            ii = ii + 1
            sheet.write(pr_cnt, ii, d['state'])
            ii = ii + 1
            sheet.write(pr_cnt, ii, time_clean(d['created_at'], time_del))
            ii = ii + 1
            sheet.write(pr_cnt, ii, time_clean(d['merged_at'], time_del))
            ii = ii + 1
            sheet.write(pr_cnt, ii, d['user']['name'])
            ii = ii + 1
            for a in d['assignees']:
                sheet.write(pr_cnt, ii, a["name"])
                ii = ii + 1

    pr_total_cnt += pr_cnt
    if pr_cnt == 0:
        print("  No PR")
    else:
        print("  ------------------------------")

if pr_total_cnt > 0:
    time_array = time.localtime(time.time())
    style_time = time.strftime("%Y-%m-%d_%H-%M-%S", time_array)
    file_name = "my_repo_pr_{:}.xls".format(style_time)
    f.save(file_name)
    print("Save to " + file_name)
